package Java_网络编程.uploadfile;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.UUID;

public class FileServer {

    public static final String Dest_File="C:\\Users\\zl\\Desktop\\A\\ServerRepository\\";
    public static void main(String[] args) throws IOException {
        System.out.println("====服务器端启动=======");
        //注册端口
        ServerSocket serverSocket = new ServerSocket(8001);
        while (true)
        {
            Socket accept = serverSocket.accept();
            System.out.println(accept.getRemoteSocketAddress()+"上线了");
            new ServerReaderThread(accept).start();
        }

    }
}
class ServerReaderThread extends Thread
{
    private Socket socket;

    public ServerReaderThread(Socket socket){
        this.socket=socket;
    }

    @Override
    public void run() {
        try {

            //新建本地C:\Users\zl\Desktop\A\ServerRepository
            String time = System.currentTimeMillis()+ "";
            BufferedOutputStream os =new BufferedOutputStream( new FileOutputStream(FileServer.Dest_File+time +".jpg"));

            InputStream sins = socket.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(sins);    //包装成高级的缓冲字节输入流

            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }

            os.flush();
            os.close();//文件复制完毕，关闭本地文件输出流
            //服务端响应接收的结果
            //得到一个字节输出流，包装成打印流
            PrintStream ps = new PrintStream(socket.getOutputStream());
            ps.println("客户端你好，服务端已经收到文件");
            ps.flush();
            Thread.sleep(10000); //等待客户端传完，让线程等待1秒
        }
        catch (Exception e)
        {
            System.out.println(socket.getRemoteSocketAddress()+"下线了");
        }

     }
}